import React from 'react';
import style from './style.process';
import * as d3 from 'd3';
import util from '../../../util';

class MyProcess extends React.Component {
  constructor(props) {
    super(props);
    this.displayName = 'MyProcess';
  }
  componentDidMount(){
    const {
      width = 170,
      height = 160,
      fields,
    } = this.props;
    const radius = Math.min(width, height) / 1.9;
    let twoPi = 2 * Math.PI;
    this.svg = d3.select(this.refs.svg).append("svg")
        .attr("width", width)
        .attr("height", height)
      .append("g")
        .attr("class", "progress-meter")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
    this.arc = d3.arc()
      .startAngle(0)
      .endAngle(function(d) { return d.value * 2 * Math.PI; })
      .innerRadius(function(d) { return d.start * radius; })
      .outerRadius(function(d) { return d.end * radius; });
    this.meter = this.svg.selectAll("g")
      .data(fields)
      .enter().append("g")

    this.meter.append("path")
        .attr("class","background")
    this.animate(); 
  }
  componentWillReceiveProps(nextProps) {
    if(!util.isShallowEqual(this.props, nextProps)){
      this.meter.data(nextProps.fields)
      this.animate();
    }
  }
  animate = () => {
    const arc = this.arc;
    this.meter
      .each(function(d) {
        this.current = this.current || 0;
        this.fill = this.fill || d.fill;
        const i = d3.interpolate(this.current, d.value);
        this.current = d.value;
        const item = d3.select(this).select('path');
        item.style('fill', this.fill).transition().duration(d.duration).style('fill', d.fill).tween("progress", function() {
          return function(t) {
            d.value = i(t);
            item.attr("d", arc(d));
          }
        });
        this.fill = d.fill;
      });
  }
  render() {
    const fields = this.props.fields.filter(v => v.text);
    return (
      <div className={style['process-area']}>
        <div ref={'svg'} key={'svg'} className={style['process-box']}>
        {this.props.label}
        </div>
        {
          !fields.length ? null :
          fields.map((v, i) => {
            return (
              <div key={i} className={style['label-box']}>
                <div className={style['label-dot']} style={{backgroundColor: v.fill}}></div>
                {v.text}
              </div>
            );
          }) 
        }
      </div>
    );
  }
}

export default MyProcess;
